package com.example.client2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private RemoteService mRemoteService;
    private Messenger mBinder;
    private TextView mTextView;
    private StringBuilder mSb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSb = new StringBuilder();
        mTextView = findViewById(R.id.testView);

        Intent intent = new Intent();
        //绑定 服务
        intent.setClassName("com.example.ipcdemo","com.example.ipcdemo.service.MessengerService");
        mRemoteService = new RemoteService();
        bindService(intent,mRemoteService, Service.BIND_AUTO_CREATE);
    }

    public void testBtn(View view) {
        Message msg = Message.obtain();
        msg.arg1 = (int) (Math.random() * 100+1);
        msg.arg2 = (int) (Math.random() * 100+1);
        mTextView.setText(mSb.toString());
        //传递 client 的 messenger ，实现服务端与客户端通信
        msg.replyTo = mMessenger;
        if (mBinder != null) {
            try {
                mBinder.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        mSb.append(msg.arg1).append(" + ").append(msg.arg2)
                .append(" = ");
    }


    Messenger mMessenger = new Messenger(new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            mSb.append(msg.arg1).append("\n");
            mTextView.setText(mSb.toString());
        }
    });



    class RemoteService implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinder = new Messenger(service);
            mSb.append("连接上服务端").append("\n");
            mTextView.setText(mSb.toString());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBinder = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRemoteService != null) {
            unbindService(mRemoteService);
        }
    }

    public void binder(View view) {
        startActivity(new Intent(this,PoolTestActivity.class));
    }


}
